import ProposalAPI from '@/api/Proposal';
import { Box, FieldCols, FormSection, mapField, useCall, useSimpleMemo } from '@/components';
import { MAIN_RISK_TYPE } from '@/constants/options';
import DescEditor from '@/pages/Comparison/CompareProduct/components/DescEditor';
import { SelectProduct } from '@/pages/components';
import { simpleMerge } from '@/utils';
import { catchAndScrollFor } from '@/utils/fp';
import { Form, Input, message } from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from 'react';
import { useDefinitionData, useUpdateDefinition } from './Context';

const SelectProductInput = ({ disabled, ...props }) => {
  const setDefinitionData = useUpdateDefinition();

  const onOk = useCall(async ([{ productCode }]) => {
    const data = await ProposalAPI.byCode({ Code: productCode });
    if (data?.data) {
      setDefinitionData(data.data);
    }
  });

  const onService = useCall((...args) => {
    return [simpleMerge(args[0], { notProposal: true })];
  });

  return (
    <SelectProduct onOk={onOk} onService={onService}>
      <Input onClick={useCall(() => !disabled)} placeholder='点击选择险种' readOnly {...props} />
    </SelectProduct>
  );
};

BasicConfig = forwardRef(BasicConfig);

function BasicConfig(props, ref) {
  const definitionData = useDefinitionData();
  const productDefine = useSimpleMemo(definitionData?.productDefineList?.[0] ?? null);
  const productType = productDefine?.productType ?? null;
  const setDefinitionData = useUpdateDefinition();
  const [form] = Form.useForm();

  useEffect(() => {
    if (productDefine) {
      form.setFieldsValue({ productDefine });
    }
  }, [productDefine]);

  const onSave = useCall(async () => {
    const formData = await form.validateFields().catch(catchAndScrollFor(form));
    const definitionPayload = {
      ...definitionData,
      productDefineList: [{ ...productDefine, ...formData.productDefine }],
    };
    await ProposalAPI.insert(definitionPayload);
    message.success('保存成功');

    if (!productDefine.id) {
      console.log('id is null');
      const data = await ProposalAPI.byCode({ Code: productDefine.productCode });
      if (data?.data) {
        setDefinitionData(data.data);
      }
    } else {
      setDefinitionData(definitionPayload);
    }
  });

  useImperativeHandle(
    ref,
    () => ({
      onSave,
    }),
    [],
  );

  const fields = useMemo(() => {
    const baseFields = [
      [['productDefine', 'productCode'], '险种编码', SelectProductInput],
      [['productDefine', 'productName'], '险种名称', null, { readOnly: true }],
    ].map(mapField);

    if (productType === MAIN_RISK_TYPE)
      return baseFields.concat(
        [
          [['productDefine', 'productShort'], '险种简称', null, { required: true }],
          [
            ['productDefine', 'productDetail'],
            '险种简介',
            'textarea',
            {
              getValueFromEvent(e) {
                let str = (e?.target?.value ?? e) || '';
                return `${str || ''}`
                  .replace(/&/g, '&amp;')
                  .replace(/</g, '&lt;')
                  .replace(/>/g, '&gt;')
                  .replace(/"/g, '&quot;')
                  .replace(/'/g, '&#039;')
                  .replace(/(\r\n|\r|\n)/g, '<br />');
              },
              getValueProps(val) {
                let value = `${val || ''}`
                  .replace(/(^\s*|\s*$)/g, '')
                  .replace(/<br\s*\/?>/g, '\r\n')
                  .replace(/&amp;/g, `&`)
                  .replace(/&lt;/g, `<`)
                  .replace(/&gt;/g, `>`)
                  .replace(/&quot;/g, `"`)
                  .replace(/&#039;/g, `'`);
                return { value };
              },
            },
          ],
        ].map(mapField),
      );
    return baseFields;
  }, [productType]);

  return (
    <FormSection title='选择险种'>
      <Box px={3}>
        <Form component={false} form={form}>
          <FieldCols form={form} fields={fields} labelSpan={6} wrapperSpan={14} colProps={useRef({ xs: 24 }).current} />
        </Form>
      </Box>
    </FormSection>
  );
}

export default BasicConfig;
